from app.db import db
from app.models.SysUserModel import SysUser
from app.decorators.checkMissingArgs import checkMissingArgs
from sqlalchemy import and_, or_
from .utils.buildFilters import build_filters

class UserService:
    @checkMissingArgs(["avatar"])
    def create_user_service(self, name, email, phone, password, role, status, avatar = ""):
        try:
            sysUser = SysUser(name=name, password=password, email=email, phone=phone, role=role, status=status, avatar=avatar)
            db.session.add(sysUser)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e
        pass

    @checkMissingArgs(['password', "avatar"])
    def update_user_service(self, id, name, email, phone, role, status, avatar):
        try:
            sysUser = SysUser.query.get(id)
            sysUser.name = name
            sysUser.email = email
            sysUser.phone = phone
            sysUser.role = role
            sysUser.status = status
            sysUser.avatar = avatar
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e

    @checkMissingArgs()
    def get_user_by_id_service(self, id):
        try:
            sysUser = SysUser.query.get(id, is_deleted=False)
            return sysUser
        except Exception as e:
            raise e
        pass



    @checkMissingArgs(['name', 'email', 'phone', 'role', 'status'])
    def get_user_list_service(self, page_num, page_size, name, email, phone, role, status):
        

        # 初始化查询条件
        filters = build_filters(model=SysUser, name=name, email=email, phone=phone, role=role, status=status, fuzzy_fields=["name", "email", "phone"])

        try:
            sysUserList = SysUser.query.filter(and_(*filters)).paginate(page=page_num, per_page=page_size, error_out=False)
            return sysUserList
        except Exception as e:
            raise e
        pass

    def get_user_total_service(self, name, email, phone, role, status):
        try:
            filters = build_filters(model=SysUser, name=name, email=email, phone=phone, role=role, status=status)
            count = SysUser.query.filter(and_(*filters)).count()
            return count
        except Exception as e:
            raise e
        pass

    @checkMissingArgs()
    def delete_user_service(self, ids: list):
        try:
            for id in ids:
                sysUser = SysUser.query.get(id)
                sysUser.is_deleted = True
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e
        pass